package enchere;

import java.io.Serializable;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.JMSException;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import exception.InvalidAuctionException;
import exception.PersonNotReferencedException;

/**
 * Implementation de l'interface enchereRemote
 *
 */
@Stateless
@LocalBean
public class EnchereBean implements EnchereRemote, Serializable{ 
	private static final long serialVersionUID = 1L;
	
	@PersistenceContext(unitName = "TestEJB")
	EntityManager entityManager;
	
	
	public EnchereBean() throws NamingException, JMSException {
		
		//SuivreEnchereJMS.initialiserJMS();
	}
	
	@Override
	public Personne inscrire(Personne personne) {
		return entityManager.merge(personne);		
	}

	@Override
	public Personne identifier(String nom, String password) throws PersonNotReferencedException {
		Personne personne = null;
		try {
			personne = (Personne) entityManager.createQuery("select p from Personne p where p.nom = '"+nom+"' and p.mdp = '"+password+"'")
					.getSingleResult();
		} catch (Exception e) {
			throw new PersonNotReferencedException("La personne n'existe pas");
		}
		return personne;
	}

	@Override
	public Article proposerArticle(Article article) {
		return entityManager.merge(article);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Article> listerArticleEnVente() {
		return entityManager.createQuery("select a from Article a where a.vendu=false").getResultList();
	}

	@Override
	public Article getArticle(int id) {
		return entityManager.find(Article.class, id);
	}
	
	@Override
	public void proposerUneEnchere(Personne personne, Article article, Double prix) throws JMSException, InvalidAuctionException {
		if((article.getPrixVente() == null && article.getPrixInitial() >= prix) || (article.getPrixVente() != null && article.getPrixVente() >= prix)){
			throw new InvalidAuctionException("Prix trop bas !!");
		}
		article.setAcheteur(personne);
		article.setPrixVente(prix);
		entityManager.merge(article);
		//SuivreEnchereJMS.suivreEnchereProducteur(article);
	}
	

		
	
}
